#include "qqserver_login.h"
//#include "ui_qqserver_login.h"
#include "proto.h"

QQserver_login::QQserver_login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QQserver_login)
{
    ui->setupUi(this);

    sd = new QUdpSocket; //udp初始化
    sd->bind(QHostAddress(RGS_IP),LOG_PORT);//绑定端口
    //链接信号与曹，当udp有消息可读时，即：客户端成功发包过来了，发送信号执行槽函数
    connect(sd,SIGNAL(readyRead()),this,SLOT(on_readyread_udp()));
}

QQserver_login::~QQserver_login()
{
    delete ui;
}

void QQserver_login::on_readyread_udp()
{
    rgs_t rcvbuf;
    QHostAddress cid;//保存客户端的ip地址
    quint16 cport;//保存客户端的端口

    //接收客户端发送过来的数据
    sd->readDatagram((char *)&rcvbuf,sizeof(rcvbuf),&cid,&cport);
    qDebug() << rcvbuf.cntbuf <<rcvbuf.pwdbuf ;

    //数据库
    QSqlDatabase sql = QSqlDatabase::addDatabase("QSQLITE");
    sql.setDatabaseName("E:\\QT Study\\build-QQ-Desktop_Qt_5_9_0_MinGW_32bit-Debug\\debug\\io_serve.dat");
    if(!sql.open())
        qDebug() << "Error:failed to connect database" << sql.lastError();
    else
        qDebug() << "succeed to connect database ";

    QSqlQuery sql_query;
    if(!sql_query.exec("create table if not exists userTable(count text primary key,password text not null)"))
        qDebug() << "Error:failed to creat database" << sql.lastError();
    else
        qDebug() << "succeed to creat database ";



    int ret;
    QString cnt;
    QString pwd;
    char buf[256];
    if(!sql_query.exec("select * from userTable"))
        qDebug() << "Error:Select error" << sql.lastError();
    else
    {
        while((ret = sql_query.next()) == true)
        {
            cnt = sql_query.value(0).toString();
            pwd = sql_query.value(1).toString();
            if(strcmp(rcvbuf.cntbuf,cnt.toLatin1().data()) == 0 && strcmp(rcvbuf.pwdbuf,pwd.toLatin1().data()) == 0)
            {
                rcvbuf.flag = LOG_OK;
                break;
            }
            if(strcmp(rcvbuf.cntbuf,cnt.toLatin1().data()) == 0)
            {
                rcvbuf.flag = LOG_EXISTS;
                break;
            }
        }
    }
    if(!ret)
    {
        rcvbuf.flag = LOG_ERROR;
    }

    sql.close();

    sd->writeDatagram((char *)&rcvbuf,sizeof(rcvbuf),cid,cport);
}
